package io.renren.controller;

import io.renren.entity.DictEmployeeEntity;
import io.renren.entity.SysUserEntity;
import io.renren.service.DictEmployeeService;
import io.renren.service.SysUserRoleService;
import io.renren.service.SysUserService;
import io.renren.service.SysWorkLogService;
import io.renren.service.xtd.DictEmployeeServiceXtd;
import io.renren.utils.Common;
import io.renren.utils.PageUtils;
import io.renren.utils.R;
import io.renren.utils.ShiroUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

/**
 * 系统用户
 * 
 * @author chenshun
 * @email sunlightcs@gmail.com
 * @date 2016年10月31日 上午10:40:10
 */
@RestController
@RequestMapping("/sys/user")
public class SysUserController extends AbstractController {
	@Autowired
	private DictEmployeeServiceXtd dictEmployeeServiceXtd;
    @Autowired
	private SysWorkLogService sysWorkLogService;
	@Autowired
	private SysUserService sysUserService;
	@Autowired
	private SysUserRoleService sysUserRoleService;
	
	/**
	 * 所有用户列表
	 */
	@RequestMapping("/list")
	@RequiresPermissions("sys:user:list")
	public R list(String username, Integer page, Integer limit){
		Map<String, Object> map = new HashMap<>();
		map.put("username", username);
		map.put("offset", (page - 1) * limit);
		map.put("limit", limit);
		
		//查询列表数据
		List<SysUserEntity> userList = sysUserService.queryList(map);
		int total = sysUserService.queryTotal(map);
		
		PageUtils pageUtil = new PageUtils(userList, total, limit, page);
		
		return R.ok().put("page", pageUtil);
	}
	
	/**
	 * 获取登录的用户信息
	 */
	@RequestMapping("/info")
	public R info(){
		return R.ok().put("user", getUser());
	}
	
	/**
	 * 修改登录用户密码
	 */
	@RequestMapping("/password")
	public R password(String password, String newPassword){
		if(StringUtils.isBlank(newPassword)){
			Common.createWorkLog(dictEmployeeServiceXtd, sysWorkLogService,
        			ShiroUtils.getUserEntity().getUsername(), "修改登录密码失败",
        			"新密码不为能空", "");
			return R.error("新密码不为能空");
		}
		
		//sha256加密
		password = new Sha256Hash(password).toHex();
		//sha256加密
		newPassword = new Sha256Hash(newPassword).toHex();
				
		//更新密码
		int count = sysUserService.updatePassword(getUserId(), password, newPassword);
		if(count == 0){
			Common.createWorkLog(dictEmployeeServiceXtd, sysWorkLogService,
        			ShiroUtils.getUserEntity().getUsername(), "更新密码失败",
        			"原密码不正确", "");
			return R.error("原密码不正确");
		}
		Common.createWorkLog(dictEmployeeServiceXtd, sysWorkLogService,
    			ShiroUtils.getUserEntity().getUsername(), "修改密码成功",
    			"", "");
		//退出
		ShiroUtils.logout();
		
		return R.ok();
	}
	
	/**
	 * 用户信息
	 */
	@RequestMapping("/info/{userId}")
	@RequiresPermissions("sys:user:info")
	public R info(@PathVariable("userId") Long userId){
		SysUserEntity user = sysUserService.queryObject(userId);
		
		//获取用户所属的角色列表
		List<Long> roleIdList = sysUserRoleService.queryRoleIdList(userId);
		user.setRoleIdList(roleIdList);
		
		return R.ok().put("user", user);
	}
	
	/**
	 * 保存用户
	 */
	@RequestMapping("/save")
	@RequiresPermissions("sys:user:save")
	public R save(@RequestBody SysUserEntity user){
		if(StringUtils.isBlank(user.getUsername())){
			Common.createWorkLog(dictEmployeeServiceXtd, sysWorkLogService,
	    			ShiroUtils.getUserEntity().getUsername(), "保存用户失败",
	    			"账号不能为空", "");
			return R.error("账号不能为空");
		}
		if(StringUtils.isBlank(user.getPassword())){
			Common.createWorkLog(dictEmployeeServiceXtd, sysWorkLogService,
	    			ShiroUtils.getUserEntity().getUsername(), "保存用户失败",
	    			"密码不能为空", "");
			return R.error("密码不能为空");
		}
		Map<String, Object> map = new HashMap<>();
		Map<String, Object> map1 = new HashMap<>();
		map.put("username", user.getUsername());
		int total = sysUserService.queryTotalByMore(map);
		if(total!=0){
			Common.createWorkLog(dictEmployeeServiceXtd, sysWorkLogService,
	    			ShiroUtils.getUserEntity().getUsername(), "保存用户失败",
	    			"此账号已被使用", "");
			return R.error("此账号已被使用");
		}


		sysUserService.save(user);


		map1.put("username",user.getUsername());
		dictEmployeeServiceXtd.in(map1);
		Common.createWorkLog(dictEmployeeServiceXtd, sysWorkLogService,
    			ShiroUtils.getUserEntity().getUsername(), "保存用户成功",
    			"", "");
		return R.ok();
	}
	
	/**
	 * 修改用户
	 */
	@RequestMapping("/update")
	@RequiresPermissions("sys:user:update")
	public R update(@RequestBody SysUserEntity user){
		if(StringUtils.isBlank(user.getUsername())){
			Common.createWorkLog(dictEmployeeServiceXtd, sysWorkLogService,
	    			ShiroUtils.getUserEntity().getUsername(), "修改用户失败",
	    			"账号不能为空", "");
			return R.error("账号不能为空");
		}
		if(StringUtils.isBlank(user.getPassword())){
			Common.createWorkLog(dictEmployeeServiceXtd, sysWorkLogService,
	    			ShiroUtils.getUserEntity().getUsername(), "修改用户失败",
	    			"密码不能为空", "");
			return R.error("密码不能为空");
		}
		Map<String, Object> map = new HashMap<>();
		map.put("username", user.getUsername());
		map.put("isnotId", user.getUserId());
		int total = sysUserService.queryTotalByMore(map);
		if(total!=0){
			Common.createWorkLog(dictEmployeeServiceXtd, sysWorkLogService,
	    			ShiroUtils.getUserEntity().getUsername(), "修改用户失败",
	    			"此账号已被使用", "");
			return R.error("此账号已被使用");
		}
		sysUserService.update(user);
		Common.createWorkLog(dictEmployeeServiceXtd, sysWorkLogService,
    			ShiroUtils.getUserEntity().getUsername(), "修改用户成功",
    			"", "");
		return R.ok();
	}
	
	/**
	 * 删除用户
	 */
	@RequestMapping("/delete")
	@RequiresPermissions("sys:user:delete")
	public R delete(@RequestBody Long[] userIds){
		if(ArrayUtils.contains(userIds, 1L)){
			Common.createWorkLog(dictEmployeeServiceXtd, sysWorkLogService,
	    			ShiroUtils.getUserEntity().getUsername(), "删除用户失败",
	    			"系统管理员不能删除", "");
			return R.error("系统管理员不能删除");
		}
		
		if(ArrayUtils.contains(userIds, getUserId())){
			Common.createWorkLog(dictEmployeeServiceXtd, sysWorkLogService,
	    			ShiroUtils.getUserEntity().getUsername(), "删除用户失败",
	    			"当前用户不能删除", "");
			return R.error("当前用户不能删除");
		}
		
		sysUserService.deleteBatch(userIds);
		Common.createWorkLog(dictEmployeeServiceXtd, sysWorkLogService,
    			ShiroUtils.getUserEntity().getUsername(), "删除用户成功",
    			"", "");
		return R.ok();
	}
	
	/**
	 * 判断是否初次登陆
	 */
	@RequestMapping(value = "/isfirstlogin")
	public R isFirst() {
		if(sysUserService.isFirstLogin(ShiroUtils.getUserId().toString())==0){
			System.out.println(sysUserService.isFirstLogin(ShiroUtils.getUserId().toString()));
			return R.ok();
		}
		return R.error();
	}
	/**
	 * 
	 * 获得角色名
	 */
	@RequestMapping("/rolename")
	@ResponseBody
	public String getRoleName(String name){
		String roleName = sysUserService.getRoleName(name);
		return roleName;
	}
	
}
